#!/bin/sh

#
# Test the MBR creation ability of fwup
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
# Numbers don't matter for the test so long as the MBR is right
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77261)

mbr mbr-01020304 {
    signature = 0x01020304

    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
mbr mbr-ffeeddcc {
    signature = 0xffeeddcc

    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}

task test1 {
	on-init {
                mbr_write(mbr-01020304)
        }
}
task test2 {
	on-init {
                mbr_write(mbr-ffeeddcc)
        }
}
EOF

# Create the firmware file
$FWUP_CREATE -c -f $CONFIG -o $FWFILE

# Run a basic test

# To create the expected images, first verify that $IMGFILE is correct and
# then run `dd if=$IMGFILE count=1 2>/dev/null | base64`
base64_decode >$WORK/expected1.img <<EOF
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAA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ILE -t test2
cmp_bytes 512 $WORK/expected2.img $IMGFILE

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
